const {PassThrough} = require('stream')

class Typer {
    #stream = new PassThrough()
    #song = '谁不是错过了四下报更的鼓声，总有人偷偷拨弄镜月的指针'
    #index = 0

    constructor(ctx) {
        // stream.setEncoding('utf8')
        // ref: https://juejin.cn/post/6965020771269902366
        // ctx.set({'Content-Type': 'text/event-stream'})
        ctx.type = 'text/event-stream';
        setInterval(this.#type, 100)
        ctx.body = this.#stream
    }

    #type = () => {
        const str = this.#song[this.#index];
        if (str) {
            // 方式1：格式是 data: xxx\n\n，事件要一对\n结束
            // this.#stream.write(`data: ${str}\n\n`)

            // 方式2,定义了event字段，自定义事件
            this.#stream.write(`event: typing\ndata: ${str}\n\n`)

            // 发送的数据为json字符串
            // this.#stream.write(`event: typing\ndata: {"name": "${str}"}\n\n`)

            this.#index++
        } else {
            this.#stream.write('0')
        }
    }
}

module.exports = {
    Typer,
}